﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RestNews.Data.Models;

namespace RestNews.Models
{
    /// <summary>
    /// New user account details
    /// </summary>
    public class NewUserAccount
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public IList<string> Roles { get; set; }
        public string Address { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }

        /// <summary>
        /// Creates the user.
        /// </summary>
        /// <param name="newUser">The new user.</param>
        /// <returns></returns>
        public long CreateUser(RestNewsContext db)
        {
            //Get the new user roles
            IList<Role> userRoles = db.Roles.Where(r => Roles.Contains(r.Name)).ToList();
            if (userRoles.Count == 0)
            {
                var readerRole = db.Roles.FirstOrDefault(r => r.Name == "Reader");
                userRoles.Add(readerRole);
            }

            
            //Create the Person Entry
            Person newPerson = new Person
            {
                FirstName = this.FirstName,
                LastName = this.LastName,
                Address = this.Address
            };

            //Create the User Entry
            User newUser = new User
            {
                Password = this.Password,
                Username = this.Username,
                Roles = userRoles,
                People = new List<Person> { newPerson }
            };

            db.Users.Add(newUser);
            db.SaveChanges();

            return newUser.People.FirstOrDefault().Id;
        }
    }
}